<template>
	<!-- 基础图片上传 -->
	<u-upload
		:fileList="imgList"
		accept="image"
		@afterRead="afterRead"
		@delete="deletePic"
		:multiple="multiple"
		name="5"
		:maxCount="1"
	></u-upload>
	
</template>

<script>
	export default {
		components: {
			
		},
		props: {
			// 图片地址
			value: [String],
			multiple: [Boolean]
		},
		data() {
			return {
				imgList: []
			}
		},
		computed: {
		},
		watch: {
			value(val){
				let {multiple, imgList} = this;
				if (multiple === false && val &&  imgList.length <= 0) {
					this.addImagePath(val);
				}
			},
		},
		mounted(){
			let value = this.value;
			if (value) {
				this.addImagePath(value);
			}
		},
		methods: {
			// 外部添加图片地址
			addImagePath(path){
				let fileItem = {
					status: 'success',
					message: '',
					url: path
				};
				this.imgList.push(fileItem);
			},
			// 删除图片
			deletePic(event) {
				console.log("删除图片：", event);
				this[`imgList`].splice(event.index, 1);
				this.$emit('input', "");
			},
			/**
			 * 新增图片
			 * @param {Object, Array} event 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			 */
			async afterRead(event) {
				console.log("新增图片", event);
				let file = event;
				this.singleUpload(file);
			},
			/**
			 * 单张图片上传
			 * @param  fileObj 图片对象
			 */
			singleUpload(fileObj){
				// 可以做成配置
				let maxSize = 2 * 1024 * 1024;
				let file = fileObj.file;
				if (file.size > maxSize) {
					uni.showToast({
						title: '图片不能超过2m',
						icon: 'none'
					});
					return;
				}
				this.$api.file.upload(file).then(({data})=>{
					let path = data.path;
					let fileItem = Object.assign(fileObj, {
						status: 'success',
						message: '',
						url: path
					});
					this.imgList.push(fileItem);
					// 绑定到值
					this.$emit('input', path);
				});
			},
		}
	}
</script>

<style>
</style>
